package com.itheima.day15.duoliao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Objects;

/**
 * 自定义线程任务类：
 * 负责和指定的客户端进行通信
 */
public class ChatRunnable implements Runnable {

    private Socket socket;

    public ChatRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                //1.获取Socket的输入流对象
                InputStream is = socket.getInputStream();
                //把原始流包装成字符输入流，更好的读取字符文本数据
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
        ) {

            //2.持续和当前客户端交互
            while (true) {

                String msg = br.readLine();
                System.out.println("接收到客户端的消息：" + msg);

                if (Objects.equals(msg, "886")) {
                    System.out.println(socket.getRemoteSocketAddress()+"：客户端强制退出...");
                    break;
                }
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress()+"：客户端强制退出...");
        }
    }

}
